package cn.itsource.controller;

import cn.itsource.dto.CourseAddDto;
import cn.itsource.service.ICourseService;
import cn.itsource.domain.Course;
import cn.itsource.query.CourseQuery;
import cn.itsource.result.JSONResult;
import cn.itsource.result.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @desc
 * @author Jason
 * @since 2022-09-01
 */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    public ICourseService courseService;

    //课程上线接口
    @PostMapping("/onLineCourse")
    @PreAuthorize("hasAuthority('course:online')")
    public JSONResult onLineCourse(@RequestBody CourseQuery query){
        return courseService.onLineCourse(query.getIds());
    }

    /**
     * 保存和修改操作公用此方法
     * @param course 前端传递来的实体数据
     */
    @PostMapping(value="/save")
    public JSONResult save(@RequestBody Course course){
        if(course.getId() != null){
            courseService.updateById(course);
        }else{
            courseService.insert(course);
        }
        return JSONResult.success();
    }

    /**
     * 根据ID删除指定对象信息
     * @param id
     */
    @DeleteMapping(value="/{id}")
    public JSONResult delete(@PathVariable("id") Long id){
        courseService.deleteById(id);
        return JSONResult.success();
    }

    //根据ID查询对象详情信息
    @GetMapping(value = "/{id}")
    public JSONResult get(@PathVariable("id")Long id) {
        return JSONResult.success(courseService.selectById(id));
    }


    /**
     * 查看所有对象数据（不分页）
     */
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('course:list')")
    public JSONResult list(){
        return JSONResult.success(courseService.selectList(null));
    }


    /**
     * 分页查询数据
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping(value = "/pagelist")
    @PreAuthorize("hasAuthority('course:pagelist')")
    public JSONResult pageList(@RequestBody CourseQuery query) {
        Page<CourseAddDto> page = courseService.selectMyPage(query);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String loginString = authentication.getPrincipal().toString();
        System.out.println("loginString=" + loginString);
        return JSONResult.success(new PageList<CourseAddDto>(page.getTotal(), page.getRecords()));
    }
}